package com.eco.fanliapp.controller.app;

import com.alibaba.fastjson.JSON;
import com.eco.fanliapp.common.base.BaseController;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.response.ResponseCode;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.AppCompany;
import com.eco.fanliapp.entity.AppUser;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.BigDecimalUtils;
import com.taobao.api.response.TbkScPublisherInfoSaveResponse.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.util.Date;

/**
 * @ProjectName: fanliapp
 * @Package: com.eco.fanliapp.controller.app
 * @ClassName: AppAuthController
 * @Author: xiaoxx
 * @Description: 获取授权之后的用户值等信息进行渠道备案
 * @Date: 2019/11/28 15:13
 * @Version: 4.2.2
 */
@RestController
public class AppAuthController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(AppAuthController.class);

    @Autowired
    private ITaoBaoService taoBaoService;
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private IAppNewsLogService appNewsLogService;
    @Autowired
    private IUserCashschemeService userCashschemeService;
    @Autowired
    private IAppCompanyService appCompanyService;

    /**
     * 授权地址
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/app/taobao/auth/url")
    @ResponseBody
    public ServerResponse<String> getAuthUrl() {
        AppUser appUser3 = appUserService.selectAppUserByUserId(getAppUser().getUserId());
        if (null != appUser3 && appUser3.getUserId() != null && appUser3.getUserId() != 0L) {
            String url = "https://oauth.taobao.com/authorize?"
                    + "response_type=token"
                    + "&client_id=" + ApiEnum.TAO_CLIENT_ID + ""
                    + "&state=" + appUser3.getUserId() + ""
                    + "&redirect_uri=" + ApiEnum.TAO_REDIRECT_URI + ""
                    + "&view=wap";
            log.info("用户{}获取授权地址{}", appUser3.getUserId(), url);
            return ServerResponse.createBySuccess("数据获取成功", url);
        } else {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ACCOUNT_ERROR.getCode(), "用户不存在");
        }
    }

    /**
     * 回调后授权登记
     *
     * @param state
     * @param taobao_open_uid
     * @param taobao_user_id
     * @param access_token
     * @return
     */
    @SuppressWarnings("deprecation")
    @RequestMapping("/app/taobao/authNew")
    public ServerResponse<String> getAuthNew(String state, String taobao_open_uid, String taobao_user_id, String access_token) {

        String appSession = access_token;
        String taobaoUserId = taobao_user_id;
        String taobaoOpenUid = taobao_open_uid;
        log.info("APP回调后授权登记-授权信息state={},taobao_open_uid={},taobao_user_id={},access_token={}", state, taobao_open_uid, taobao_user_id, access_token);
        if (null != state) {
            AppUser appUser3 = appUserService.selectAppUserByUserId(Long.valueOf(state));
            if (appUser3 != null) {
                log.info("APP回调后授权登记-stateUserId={},用户数据{}", state, JSON.toJSONString(appUser3));
                //RelationId 等于”“或者等于0代表没有渠道ID
                //查询所属公司
                AppCompany com = appCompanyService.selectAppCompanyById(appUser3.getCompanyId());
                if (appUser3.getRelationId() == null || appUser3.getRelationId() == 0) {

                    ServerResponse<Data> response = taoBaoService.getRelationId2(com.getInviteCode(), appSession, com.getInviteCode() + "." + com.getCompanyId().toString(), appUser3.getUserId());
                    log.info("APP回调后授权登记-渠道授权结果user_id={},inviteCode={},response={}", appUser3.getUserId(), com.getInviteCode(), JSON.toJSONString(response));
                    if (response != null && response.getStatus() == ResponseCode.SUCCESS.getCode()) {
                        //渠道关系ID
                        AppUser us = appUserService.selectUserInfoByRelationId(
                                Long.valueOf(response.getData().getRelationId()));
                        if (null == us) {
                            AppUser appUser = new AppUser();
                            appUser.setTableId(appUser3.getTableId());
                            //渠道关系ID
                            appUser.setRelationId(Long.valueOf(response.getData().getRelationId()));
                            appUser.setRelationName(URLDecoder.decode(response.getData().getAccountName()));
                            appUser.setTaobaoOpenUid(taobaoOpenUid);
                            appUser.setTaobaoUserId(Long.valueOf(taobaoUserId));
                            appUser.setUserTaobaoAuthorization(2);
                            appUser.setInviteCode(com.getInviteCode());
                            appUser.setSchemeId(com.getTaoBaoScheme().getId());
                            appUser.setUserAuthorizationTime(new Date());
                            appUser.setUserUpdateTime(System.currentTimeMillis());
                            int i = appUserService.updateAppUser(appUser);
                            //授权后重新获取用户信息并刷新redis
                            appUser3 = appUserService.selectAppUserByUserId(appUser3.getUserId(), 0);
                            if (i > 0) {
                                log.info("APP回调后授权登记-用户渠道信息授权成功userId={}，relationId={}", appUser3.getUserId(), appUser.getRelationId());
                                //发送消息
                                appNewsLogService.newsType(appUser3.getUserId(),
                                        NewsEnumLog.NEWS_TAOBAO.getNewsType(),
                                        BigDecimalUtils.Format(NewsEnumLog.NEWS_TAOBAO.getNewsMoeny()));
                                return ServerResponse.createBySuccessMessage("授权成功");
                            } else {
                                log.info("APP回调后授权登记-用户渠道信息授权失败userId={}，relationId={}", appUser3.getUserId(), appUser.getRelationId());
                                return ServerResponse.createByErrorMessage("授权失败");
                            }
                        } else {
                            log.info("APP回调后授权登记-渠道已在其他账号授权过了userId={}，relationId={}", appUser3.getUserId(), response.getData().getRelationId());
                            return ServerResponse.createByErrorMessage("您已在其他账号授权过了，快去购物吧");
                        }
                    }
                } else {
                    //RelationId不为空或不等于0代表已经获取到渠道ID
                    log.info("用户重复授权--userId={},获取到的用户渠道ID为{}", appUser3.getUserId(), appUser3.getRelationId());
                    return ServerResponse.createByErrorMessage("您已经授权过了，快去购物吧");
                }
                if (appUser3.getSpecialId() == null || appUser3.getSpecialId() == 0) {
                    //如果渠道授权失败
                    if (com.getMinviteCode() == null || "".equals(com.getMinviteCode())) {
                        log.info("APP回调后授权登记-公司会员邀请码为空，授权失败userId={}", appUser3.getUserId());
                        return ServerResponse.createByErrorMessage("很抱歉，系统检测到您当前的淘宝账户存在安全隐患，\n" +
                                "无法授权，请更换其他常用的淘宝账户再次授权");
                    } else {
                        //上面进行渠道授权，渠道授权失败进行会员id授权
                        ServerResponse<Data> response = taoBaoService.getSpecialId2(com.getMinviteCode(), appSession, com.getMinviteCode() + "." + com.getCompanyId().toString(), appUser3.getUserId());
                        log.info("APP回调后授权登记-会员授权结果user_id={},minviteCode={},response={}", appUser3.getUserId(), com.getMinviteCode(), JSON.toJSONString(response));
                        if (response != null && response.getStatus() == ResponseCode.SUCCESS.getCode()) {
                            //会员运营ID
                            AppUser us = appUserService.selectUserInfoBySpecialId(
                                    Long.valueOf(response.getData().getSpecialId()));
                            if (null == us) {
                                AppUser appUser = new AppUser();
                                appUser.setTableId(appUser3.getTableId());
                                //会员运营ID
                                appUser.setSpecialId(Long.valueOf(response.getData().getSpecialId()));
                                appUser.setRelationName(URLDecoder.decode(response.getData().getAccountName()));
                                appUser.setTaobaoOpenUid(taobaoOpenUid);
                                appUser.setTaobaoUserId(Long.valueOf(taobaoUserId));
                                appUser.setUserTaobaoAuthorization(2);
                                appUser.setInviteCode(com.getMinviteCode());
                                appUser.setSchemeId(com.getTaoBaoScheme().getId());
                                appUser.setUserAuthorizationTime(new Date());
                                appUser.setUserUpdateTime(System.currentTimeMillis());
                                int i = appUserService.updateAppUser(appUser);
                                //授权后重新获取用户信息并刷新redis
                                appUser3 = appUserService.selectAppUserByUserId((appUser3 == null ? null : appUser3.getUserId()), 0);
                                if (i > 0) {
                                    log.info("APP回调后授权登记-用户会员信息授权成功userId={}，specialId={}", (appUser3 == null ? null : appUser3.getUserId()), (appUser == null ? null : appUser.getSpecialId()));
                                    appNewsLogService.newsType(appUser3.getUserId(),
                                            NewsEnumLog.NEWS_TAOBAO.getNewsType(),
                                            BigDecimalUtils.Format(NewsEnumLog.NEWS_TAOBAO.getNewsMoeny()));
                                    return ServerResponse.createBySuccessMessage("授权成功");
                                } else {
                                    log.info("APP回调后授权登记-用户会员信息授权失败userId={}，specialId={}", (appUser3 == null ? null : appUser3.getUserId()), (appUser == null ? null : appUser.getSpecialId()));
                                    return ServerResponse.createByErrorMessage("授权失败");
                                }
                            } else {
                                log.info("APP回调后授权登记-会员已在其他账号授权过了userId={}，specialId={}", (appUser3 == null ? null : appUser3.getUserId()), response.getData().getSpecialId());
                                return ServerResponse.createByErrorMessage("您已在其他账号授权过了，快去购物吧");
                            }
                        } else {
                            log.info("APP回调后授权登记-用户会员信息获取失败userId={}", appUser3.getUserId());
                            return ServerResponse.createByErrorMessage("很抱歉，系统检测到您当前的淘宝账户存在安全隐患，\n"+
                                    "无法授权，请更换其他常用的淘宝账户再次授权");
                        }
                    }
                } else {
                    //RelationId不为空或不等于0代表已经获取到渠道ID
                    log.info("用户重复授权--userId={},获取到的用户会员ID为{}", appUser3.getUserId(), appUser3.getSpecialId());
                    return ServerResponse.createByErrorMessage("您已经授权过了，快去购物吧");
                }
            } else {
                return ServerResponse.createByErrorCodeMessage(301, "请重新登陆");
            }
        }
        return ServerResponse.createByErrorCodeMessage(301, "用户信息获取失败");
    }

}


